package cn.newhopedairy.sim.api;

import cn.newhopedairy.sim.applicationq.IEndpointService;
import cn.newhopedairy.sim.infrastructure.db.po.EndpointPo;
import cn.newhopedairy.common.utils.Tree;
import com.wf.captcha.utils.CaptchaUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author Neo.Li
 * @date 2021-01-0610:42
 */
@Slf4j
@Controller
public class MainController {
    @Autowired
    IEndpointService endpointService;

    @GetMapping("/user/me")
    @ResponseBody
    public Authentication user(Authentication authentication) {
        return authentication;
    }

    @GetMapping("/login")
    String login() {
        return "/system/login";
    }

    @GetMapping("/dashboard")
    String dashboard(Model model) {
        setModel(model);
        return "/system/dashboard";
    }

    @GetMapping("/user")
    String user(Model model) {
        setModel(model);
        return "/system/user";
    }

    @GetMapping("/menu")
    String menu(Model model) {
        setModel(model);
        return "/system/menu";
    }

    @GetMapping("/error")
    String error() {
        return "/system/error";
    }

    @GetMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //CaptchaUtil已经将captcha放入了session，用request.getSession().getAttribute("captcha");获取
        CaptchaUtil.out(request, response);
    }

    private void setModel(Model model) {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User user = (User)principal;

        List<EndpointPo> menuEntities = endpointService.list();
        List<Tree<EndpointPo>> tempList = new ArrayList<>();
        for (EndpointPo menuUri : menuEntities) {
            Tree<EndpointPo> tree = new Tree<>();
            tree.setId(menuUri.getId().toString());
            tree.setParentId(menuUri.getParentId().toString());
            tree.setText(menuUri.getEndpointName());
            Map<String, Object> attributes = new HashMap<>(2);
            attributes.put("url", menuUri.getEndpointUri());
            attributes.put("icon", menuUri.getIcon());
            tree.setAttributes(attributes);

            tempList.add(tree);
        }

        model.addAttribute("menu_tree", Tree.buildTree(tempList));
        model.addAttribute("username", user.getUsername());
    }
}
